﻿using Sunny.UI;
using System;
using System.IO.Pipes;
using System.IO;
using System.Threading;
using CoreShop.Model.FromBody;
using CoreShop.Library;
using CoreShop.Model;
using System.Collections.Generic;
using CoreShop.Services.Services.Report;
using CoreShop.App.Units;
using System.Windows.Forms;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using static CoreShop.Library.GlobalEnumVars;
using CoreShop.Services;
using System.Reflection;
using CoreShop.PrintService;
using gregn6Lib;

namespace CoreShop.App
{
    public partial class fpgClassList : UIPage
    {
        public int mPageIndex = 0;
        List<ClassDataDto> classDataList = new List<ClassDataDto>();
        ClassDataDto classData;
        private bool isLoadData = false;
        private Axgregn6Lib.AxGRPrintViewer axGRPrintViewer1 = new Axgregn6Lib.AxGRPrintViewer();
        private GridppReport Report = new GridppReport();
        protected GridppReport SubFoodType = new GridppReport();//商品分类

        public fpgClassList()
        {
            InitializeComponent();
            //try
            //{
            //    this.axGRPrintViewer1 = new AxgrproLib.AxGRPrintViewer();
            //    ((System.ComponentModel.ISupportInitialize)(this.axGRPrintViewer1)).BeginInit();
            //    this.axGRPrintViewer1.Dock = System.Windows.Forms.DockStyle.Fill;
            //    this.axGRPrintViewer1.Enabled = true;
            //    this.axGRPrintViewer1.Location = new System.Drawing.Point(0, 0);
            //    this.axGRPrintViewer1.Name = "axGRPrintViewer1";
            //    this.axGRPrintViewer1.Size = new System.Drawing.Size(712, 470);
            //    this.axGRPrintViewer1.TabIndex = 1;
            //    this.pnlGridReport.Controls.Add(this.axGRPrintViewer1);
            //    ((System.ComponentModel.ISupportInitialize)(this.axGRPrintViewer1)).EndInit();

            //    var schemedetail = AppConstVars.printServices.PrintSchemeInfo.printschemedetails.Find(p => p.billtypeId == (int)GlobalEnumVars.PrintbillType.ClassBill);
            //    var billtemplate = schemedetail.billtemplate;
            //    if (billtemplate == null) return;
            //    if (!string.IsNullOrEmpty(billtemplate.reportFile))
            //    {
            //        var mFileName = System.Windows.Forms.Application.StartupPath + "\\report\\" + billtemplate.reportFile;
            //        Report.LoadFromFile(mFileName);
            //        axGRPrintViewer1.Report = Report;
            //    }
            //}
            //catch { }
        }

        private void fpgClassList_ReceiveParams(object sender, UIPageParamsArgs e)
        {
            mPageIndex = 1;
            var rptRequest = e.Value as PosReportRequest;
            if (rptRequest.type == (int)GlobalEnumVars.ReportRequest.Query)
            {
                LoadData(rptRequest);
            }
            else
            {
                ExportData();
            }
        }

        private void ReportFetchRecord()
        {
            try
            {
                if (classData == null) return;
                if (classData.payments.Count == 0) return;
                var paymentModel = classData.payments.First();
                PropertyInfo[] properties1 = paymentModel.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                Report.DetailGrid.Recordset.Empty();
                foreach (var payment in classData.payments)
                {
                    Report.DetailGrid.Recordset.Append();

                    #region 商品明细与Grid++Report记录集的字段之间的对应关系
                    foreach (PropertyInfo item1 in properties1)
                    {
                        string name = item1.Name;
                        object value = item1.GetValue(payment, null);

                        foreach (IGRField fld in Report.DetailGrid.Recordset.Fields)
                        {
                            if (String.Compare(fld.RunningDBField, name, true) == 0)
                            {
                                fld.Value = value;
                                break;
                            }
                        }
                    }
                    #endregion

                    #region 与Grid++Report记录集的字段之间的对应关系
                    if (classData != null)
                    {
                        PropertyInfo[] properties2 = classData.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                        foreach (PropertyInfo item2 in properties2)
                        {
                            string name = item2.Name;
                            object value = item2.GetValue(classData, null);

                            foreach (IGRField fld in Report.DetailGrid.Recordset.Fields)
                            {
                                if (String.Compare(fld.RunningDBField, name, true) == 0)
                                {
                                    fld.Value = value;
                                    break;
                                }
                            }
                        }
                    }
                    #endregion

                    Report.DetailGrid.Recordset.Post();
                }
            }
            catch { }
        }

        //在C#中一次填入一条记录不能成功，只能使用一次将记录全部填充完的方式
        private void ReportFetchRecord_SubFoodType()
        {
            //获取子报表的内部报表对象  
            try
            {
                SubFoodType.DetailGrid.Recordset.Empty();
                if ((classData.foodTypes == null) || (classData.foodTypes.Count == 0)) return;
                var foodTypeInfo = classData.foodTypes.First();
                PropertyInfo[] properties1 = foodTypeInfo.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (var foodType in classData.foodTypes)
                {
                    SubFoodType.DetailGrid.Recordset.Append();

                    #region 分类明细与Grid++Report记录集的字段之间的对应关系
                    foreach (PropertyInfo item1 in properties1)
                    {
                        string name = item1.Name;
                        object value = item1.GetValue(foodType, null);

                        foreach (IGRField fld in SubFoodType.DetailGrid.Recordset.Fields)
                        {
                            if (String.Compare(fld.RunningDBField, name, true) == 0)
                            {
                                fld.Value = value;
                                break;
                            }
                        }
                    }
                    #endregion                    

                    SubFoodType.DetailGrid.Recordset.Post();
                }
            }
            catch
            { }
        }


        private void LoadOrderDetail(long classId)
        {
            try
            {
                classData = new corecmsfoodorderclassServices().GetClassData(classId);
                if (classData == null) return;
                //classData.sum_posAmount = classData.Consumption.Sum(p => p.Amount);
                //classData.sum_depAmount = classData.userDeposits.Sum(p => p.Amount);
                //classData.sum_allAmount = classData.userDeposits.Sum(p => p.Amount) + classData.Consumption.Sum(p => p.Amount);
                //classData.userGiftAmount = CommFunc.ConvertToDecimal(classData.userDeposits.Sum(p => p.giftAmount));               
                //Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                //try
                //{
                //    SubFoodType = Report.ControlByName("SubFoodType").AsSubReport.Report;
                //    SubFoodType.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord_SubFoodType);
                //}
                //catch { }
                //axGRPrintViewer1.Stop();
                //axGRPrintViewer1.Report = Report;
                //axGRPrintViewer1.Start();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                HideStatusForm();
            }
        }


        private void ExportData()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.Title = "Export Excel File To";
            saveFileDialog.ShowDialog();
            string fileName = saveFileDialog.FileName;
            if (fileName == "") return;
            Dictionary<string, DataGridView> gridViews = new Dictionary<string, DataGridView>();
            gridViews.Add("销售汇总", dgvClassOffList);
            if (ExportUtil.NPOIExportForDataGridview(gridViews, fileName))
            {
                MessageBox.Show("导出Excel成功！");
            }
        }


        /// <summary>
        ///销售统计
        /// </summary>
        private void LoadData(PosReportRequest posReport)
        {
            try
            {
                isLoadData = true;
                int count = 0;
                classDataList = new corereportServices().GetclassOff(ref count, mPageIndex
                    , btnPg6.PageSize, posReport.starTime, posReport.endTime, this.txt6_classNumber.Text);
                btnPg6.TotalCount = count;
                this.dgvClassOffList.AutoGenerateColumns = false;
                this.dgvClassOffList.DataSource = classDataList;
                //uiDataGridViewFooter1.DataGridView = sumRow;
                //设置统计绑定的表格
                PageTotal.DataGridView = dgvClassOffList;
                PageTotal["className"] = "合计：";
                PageTotal["allCount"] = CommFunc.ConvertToString(classDataList.Sum(p => p.allCount));
                PageTotal["allFoodCount"] = CommFunc.ConvertToString(classDataList.Sum(p => p.allFoodCount));
                PageTotal["sumShouldAmount"] = CommFunc.ConvertToString(classDataList.Sum(p => p.sumShouldAmount));
                PageTotal["column6_sumRealAmount"] = CommFunc.ConvertToString(classDataList.Sum(p => p.sumRealAmount));
                PageTotal["column6_sumAllAmount"] = CommFunc.ConvertToString(classDataList.Sum(p => p.sumRealAmount));
                PageTotal["sum_posAmount"] = CommFunc.ConvertToString(classDataList.Sum(p => p.sum_posAmount));
                PageTotal["sum_depAmount"] = CommFunc.ConvertToString(classDataList.Sum(p => p.sum_depAmount));
                if (classDataList.Count > 0)
                {
                    var classData = classDataList.First();
                    LoadOrderDetail(classData.classId);
                }
            }
            finally
            {
                isLoadData = false;
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (dgvClassOffList.SelectedRows.Count == 1)
            {
                long classId = CommFunc.ConvertToInt64(dgvClassOffList.SelectedRows[0].Cells["classId"].Value);
                if (classId == 0)
                {
                    UIMessageBox.Show("未选择需要打印的数据，无法打印", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                //classOffPrint(out classData, classId);
                classData = new corecmsfoodorderclassServices().GetClassData(classId);
            }
            new PrintServices().SetPrintClassBill(classData, false);
        }

        private void classOffPrint(out ClassDataDto classData, long classId)
        {
            classData = classDataList.Where(p => p.classId == classId).First();
            if (classData == null) return;
            classData.foodTypes = new corereportServices().GetClassFoodType(classId);

            classData.payments = new List<ClassPayment>();
            classData.payments.Clear();
            List<corecmspayments> pms = new corecmspaymentsService().SelectDataAll();
            foreach (var item in pms)
            {
                var cons = classData.Consumption.Where(p => p.payMentName.Equals(item.name)).ToList();
                var users = classData.userDeposits.Where(p => p.payMentName == item.name).ToList();
                if (cons.Count > 0 || users.Count > 0)
                {
                    decimal conAmount = cons.Count > 0 ? cons[0].Amount : 0;
                    decimal userAmount = users.Count > 0 ? users[0].Amount : 0;
                    ClassPayment payment = new ClassPayment()
                    {
                        payName = item.name,
                        posAmount = conAmount,
                        depAmount = userAmount,
                        allAmount = conAmount + userAmount
                    };
                    classData.payments.Add(payment);
                }
            }
        }

        private void btnSettlementUn_Click(object sender, EventArgs e)
        {
            if (dgvClassOffList.SelectedRows.Count == 1)
            {
                long classId = CommFunc.ConvertToInt64(dgvClassOffList.SelectedRows[0].Cells["classId"].Value);
                if (classId == 0)
                {
                    UIMessageBox.Show("未选择需要打印的数据，无法打印", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                // classOffPrint(out classData, classId);
                classData = new corecmsfoodorderclassServices().GetClassData(classId);
            }
            new PrintServices().SetPrintClassBill(classData, true);
        }

        private void dgvClassOffList_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (isLoadData) return;
                int a = dgvClassOffList.CurrentRow.Index;
                long classId = CommFunc.ConvertToInt64(dgvClassOffList.Rows[a].Cells["classId"].Value);
                LoadOrderDetail(classId);
            }
            catch
            {

            }
        }
    }
}